package org.gr.ias.user.controller;

import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.gr.ias.common.entity.SysUser;
import org.gr.ias.user.pojo.LoginFormData;
import org.gr.ias.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户管理
 */
@Log4j
@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    public static final String SUCCESS = "success";
    public static final String ERROR_INFO = "errorInfo";
    public static final String CHECK_CODE = "checkcode";
    public static final String CURRENT_USER = "currentUser";
    public static final int INITIAL_CAPACITY = 16;
    /**
     * 用户登录
     */
    @ResponseBody
    @RequestMapping("/login")
    public Map<String,Object> login(@Valid LoginFormData loginFormData, BindingResult bindingResult, HttpSession session){
        // 执行后端的表单数据验证
        Map<String,Object> map=new HashMap<>();
        Subject subject= SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(loginFormData.getUserName(),loginFormData.getPassword());
        try{
            log.info(loginFormData.getUserName()+"准备登录系统……");
            // 登录认证
            subject.login(token);
            log.info(loginFormData.getUserName()+"成功登录系统……");
            // 根据用户名查询用户详细信息
//            String userName=(String) SecurityUtils.getSubject().getPrincipal();
//            Example tuserExample=new Example(SysUser.class);
//            tuserExample.or().andEqualTo("userName",userName);
//            SysUser currentUser=userService.selectByExample(tuserExample).get(0);
//            session.setAttribute(CURRENT_USER, currentUser);
            // 设置返回数据
            map.put("succ", "yes");
            System.out.println("我的map："+map);
            map.put("mesg","err");
            return map;
        }catch(Exception e){
            e.printStackTrace();
            map.put("succ", "false");
            map.put("errorInfo", "用户名或者密码错误！");
            log.info(loginFormData.getUserName()+"登录失败，原因：用户名或者密码错误");
            System.out.println("我的map："+map);
            return map;
        }
    }

}
